<?php

namespace app\api\controller;

use app\admin\model\Helper;
use app\api\ApiHandle;
use app\common\controller\Api;
use app\common\controller\Util;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use fast\Random;
use think\Db;
use think\Exception;
use think\Hook;
use function fast\e;

/**
 * 示例接口
 */
class Bizhelper extends ApiHandle
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Helper;
    }
    private function addHelper2Admin($username, $password, $email = '', $mobile = '', $nick_name = '', $extend = [])
    {
        //账号注册时需要开启事务,避免出现垃圾数据
        try {
            $params['username'] = $username;
            $params['nickname'] = $nick_name;
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($password) . $params['salt']);
            $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            Db::name("admin")->insert($params);
            return Db::getLastInsID();
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    private function addHelper2User($username, $password, $email = '', $mobile = '', $nick_name = '', $extend = [])
    {
        if (User::getByUsername($username)) {
            throw new Exception($username . '已存在');
        }
        if ($mobile && User::getByMobile($mobile)) {
            throw new Exception($mobile . '已存在');
        }
        $ip = request()->ip();
        $time = time();
        $data = [
            'username' => $username,
            'nickname' => $nick_name,
            'password' => $password,
            'email' => $email,
            'mobile' => $mobile,
            'level' => 1,
            'score' => 0,
            'avatar' => '',
            'group_id' => '3'
        ];
        $params = array_merge($data, [
            'salt' => Random::alnum(),
            'jointime' => $time,
            'joinip' => $ip,
            'logintime' => $time,
            'loginip' => $ip,
            'prevtime' => $time,
            'status' => 'normal'
        ]);
        $params['password'] = $this->getEncryptPassword($password, $params['salt']);
        $params = array_merge($params, $extend);
        $user = User::create($params, true);
        return $user;
    }

    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt 密码盐
     * @return string
     */
    private function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/9/3
     * @Time: 11:07
     * @Interface addhelper
     * 添加助教接口 思路
     * 校验手机号，邀请码，添加用户到admin表，助教表。
     */
    public function addhelper()
    {
        if ($this->request->isPost()) {
            $param = $this->request->post();
            $name = $param['name'];
            $nick_name = $param['nick_name'];
            $phone = $param['phone'];
            $code = $param['code'];
            $investCode = $param['investCode'] ?? '';
            $password = $param['password'];

            $tid = 0;
            if ($param) {
                // 数据校验START
                $data = $this->validate($param, [
                    'phone' => 'require|regex:/^1[3456789]\d{9}$/',
                    'password' => 'require|regex:/^[0-9a-z_.]{8,16}$/i',
                ], [
                        'phone.require' => '手机号码必填',
                        'phone.regex' => '手机号码格式错误',
                        'password.require' => '密码为必填',
                        'password.regex' => '密码格式为8-16位大小写字母、数字、特殊符号',
                    ]
                );
                if (!empty($data) && $data !== true) {
                    return $this->error($data);
                }
                //查询老师
                $user_id = $this->auth->id;
                if ($user_id) {
                    $teacher = Db::name('teacher')->where('user_id', $user_id)->find();
                    if ($teacher) {
                        $params['teacher_id'] = $teacher['id'];
                    } else {
                        return $this->error('当前用户不是老师');
                    }
                } else {
                    return $this->error('当前教师不存在');
                }

//                todo 暂时注销验证码校验
                $this->checkPhone($code, $phone);
                Db::startTrans();
                try {
                    //教师添加助教
                    //添加到user表，同时添加group_id
                    $ret = $this->addHelper2User($phone, $password, '', $phone, $nick_name, []);
                    $user = $ret;
                    if ($ret) {
                    // res作为admin的id标识
                    // 插入admin表
                        $ret = $this->addHelper2Admin($phone, $password, '', $phone, $nick_name, []);
                        //助教角色 4
                        Db::name("auth_group_access")->insert(['uid' => $ret, 'group_id' => 4]);
                    }

                    if ($ret) {
                        $params['invite_code'] = Util::getInviteCode();
                        $params['user_id'] = $user['id'];
                        $params['admin_id'] = $ret;
                        $params['phone'] = $param['phone'];
                        $params['nick_name'] = $param['nick_name'];
                        $params['name'] = $param['phone'];
                        $params['create_time'] = date("Y-m-d H:i:s");

                        //            插入helper表
                        Db::name('helper')->insert($params);
                        $tid = Db::name("helper")->getLastInsID();
                        $hooks_data = [
                            // 用户姓名
                            'name' => $nick_name,
                            // 用户所在表id
                            'uid' => $tid,
                            // 用户类型 student / teacher / help
                            'type' => 'help',
                        ];
                        Hook::listen("createAccountForUser", $hooks_data, '', true);
//                        添加钩子，邀请码
                        if (!empty($param['by_invite_code'])) {
                            // 分销模块
                            $hooks_data = [
                                'uid' => $tid,
                                'role' => 'help',
                                'invite_code' => $investCode,
                            ];
                            Hook::listen("createTeacherInvest", $hooks_data);
                        }
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
//                    $this->error("添加异常");
                }
            }
            $result['id'] = $tid;
            return $this->success('添加成功', $result);
        }
        return $this->success('请发送post请求');
    }
    /**
     * 助教列表
     *
     */
    public function helperList()
    {
        $param = $this->request->post();
        $nick_name = $param['nick_name'];
        $user_id = $this->auth->id;
        $teacher = Db::name('teacher')->where('user_id', $user_id)->find();
        $filter = [
            'teacher_id' => $teacher['id'],
        ];
        $op = [
            'teacher_id' => "=",
        ];
        if (!empty($nick_name)) {
            $filter['nick_name'] = '%' . $nick_name . '%';
            $op['nick_name'] = 'like';
        }
        if (!$teacher) {
            return $this->error('教师请登录');
        }
        $result = $this->indexed($filter, $op);
        return $this->success('返回成功', $result);
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/9/3
     * @Time: 16:44
     * @Interface doFreen
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *  冻结助教
     */
    public function doFreen()
    {
        $params = $this->request->post();
        $id = $params['id'];
        if ($id) {
            $helper = Db::name('helper')->where('id', $id)->find();
            if (!$helper) {
                return $this->error('助教不存在');
            }
            if ($helper['account_status'] === '0') {
                //解冻
                Util::changeAdminOrUser($helper['admin_id'], '1', $helper['user_id']);
                Db::name('helper')->where('id', $helper['id'])->update(['account_status' => '1']);
            }
            if ($helper['account_status'] === '1') {
//                冻结
                Util::changeAdminOrUser($helper['admin_id'], '0', $helper['user_id']);
                Db::name('helper')->where('id', $helper['id'])->update(['account_status' => '0']);
            }
        }
        return $this->success('操作成功');

    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/9/3
     * @Time: 17:18
     * @Interface reset
     * 重置密码
     */
    public function reset()
    {
        $param = $this->request->post();
        $password = $param['password'];
        $id = $param['id'];
        $data = $this->validate($param, [
            'password' => 'require|regex:/^[0-9a-z_.]{8,16}$/i',
        ], [
                'password.require' => '密码为必填',
                'password.regex' => '密码格式为8-16位大小写字母、数字、特殊符号',
            ]
        );
        if (!empty($data) && $data !== true) {
            return $this->error($data);
        }


        $helper = Helper::get($id);

        $code = $param['code'];
//        todo 手机验证码校验
        $this->checkPhone($code, $helper['phone']);
        if (!$helper) {
            return $this->error('用户不存在');
        }

        Db::startTrans();
        try {
            $params['id'] = $helper['admin_id'];
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($password) . $params['salt']);
//                更新admin表和user表
            Db::name('admin')->update($params);
            $params['id'] = $helper['user_id'];
            Db::name('user')->update($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
        }
        return $this->success('重置密码成功');

    }
    private function checkPhone($code, $phone)
    {
        $ret = Smslib::check($phone, $code, 'register');
        return '';
        if (!$ret) {
            $this->error(__('验证码不正确'));
        }
    }

}
